<template>
  <div class="cart">
    <h4>全部商品</h4>
    <div class="cart-main">
      <div class="cart-th">
        <div class="cart-th1">全部</div>
        <div class="cart-th2">商品</div>
        <div class="cart-th3">单价（元）</div>
        <div class="cart-th4">数量</div>
        <div class="cart-th5">小计（元）</div>
        <div class="cart-th6">操作</div>
      </div>
      <div class="cart-body">
        <ul
          class="cart-list"
          v-for="cartInfo in cartInfoList"
          :key="cartInfo.skuId"
        >
          <li class="cart-list-con1">
            <input
              type="checkbox"
              :checked="!!cartInfo.isChecked"
              @click="checkCartInfoState(cartInfo)"
              name="chk_list"
            />
          </li>
          <li class="cart-list-con2">
            <img :src="cartInfo.imgUrl" />
            <div class="item-msg">
              {{ cartInfo.skuName }}
            </div>
          </li>
          <li class="cart-list-con4">
            <span class="price">{{ cartInfo.skuPrice }}</span>
          </li>
          <li class="cart-list-con5">
            <a @click="changeSkuNum('decrement', cartInfo)" class="mins">-</a>
            <input
              autocomplete="off"
              type="text"
              :value="cartInfo.skuNum"
              minnum="1"
              class="itxt"
              @change="changeSkuNum('change', cartInfo, $event)"
            />
            <a @click="changeSkuNum('increment', cartInfo)" class="plus">+</a>
          </li>
          <li class="cart-list-con6">
            <span class="sum">{{ cartInfo.skuPrice * cartInfo.skuNum }}</span>
          </li>
          <li class="cart-list-con7">
            <a @click="showDialogByDelOneCartInfo(cartInfo)" class="sindelet"
              >删除</a
            >
            <br />
            <a href="#none">移到收藏</a>
          </li>
        </ul>
      </div>
    </div>
    <div class="cart-tool">
      <div class="select-all">
        <input class="chooseAll" type="checkbox" v-model="cheakAll" />
        <span>全选</span>
      </div>
      <div class="option">
        <a @click="showDialogByDelSelected">删除选中的商品</a>
        <a href="#none">移到我的关注</a>
        <a href="#none">清除下柜商品</a>
      </div>
      <div class="money-box">
        <div class="chosed">
          已选择 <span>{{ seletedCount }}</span
          >件商品
        </div>
        <div class="sumprice">
          <em>总价（不含运费） ：</em>
          <i class="summoney">{{ selectedMoney }}</i>
        </div>
        <div class="sumbtn">
          <a class="sum-btn" target="_blank" @click="$router.push('/trade')"
            >结算</a
          >
        </div>
      </div>
    </div>
    <!-- 使用Dialog弹框 -->
    <Dialog :visible.sync="visible" v-show="visible">
      <template v-slot:header> 提示 </template>
      <template> 此操作将永久删除数据，是否继续？ </template>
      <template #footer>
        <div class="btn-footer">
          <button class="btn" @click="visible = false">取消</button>
          <button class="btn primary" @click="delCartInfo">确认</button>
        </div>
      </template>
    </Dialog>
  </div>
</template>

<script>
import { skuNumReg } from "../../utils/reg";
import { debounce } from "../../utils/debounce";
import {
  reqShopCartListData,
  reqChangeShopCartInfoState,
  reqChangeAllCartState,
  reqDelOneShopCartInfo,
  reqDelSelectedShopCartInfo,
  reqAddOrUpdateCart,
} from "../../api";

export default {
  data() {
    return {
      answer: "",
      timer: null,
      cartInfoList: [],
      visible: false,
      skuId: 0,
      isDelOne: false,
      skuIdList: [],
      leftCartInfoList: [],
      num: 0,
    };
  },
  name: "ShopCart",
  async mounted() {
    this.getShopCartListData();
  },
  methods: {
    async getShopCartListData() {
      const result = await reqShopCartListData();
      console.log("shopcart", result);
      if (result.code === 200) {
        console.log(result);
        this.cartInfoList = result.data[0].cartInfoList;
      } else {
        console.log(result.message);
      }
    },
    //
    async checkCartInfoState(cartInfo) {
      let isChecked = 1 - cartInfo.isChecked;
      reqChangeShopCartInfoState(cartInfo.skuId, isChecked);
      cartInfo.isChecked = isChecked;
    },
    // 单个删除
    async showDialogByDelOneCartInfo(cartInfo) {
      (this.visible = true), (this.isDelOne = true);
      this.skuId = cartInfo.skuId;
    },
    // 批量删除
    async showDialogByDelSelected() {
      {
        (this.visible = true), (this.isDelOne = false);
        (this.skuIdList = []),
          this.cartInfoList.forEach((cartInfo) => {
            if (cartInfo.isChecked === 1) {
              this.skuIdList.push(cartInfo.skuId);
            } else {
              this.leftCartInfoList.push(cartInfo);
            }
          });
      }
    },
    // 对话框确定
    async delCartInfo() {
      if (this.isDelOne) {
        const result = await reqDelOneShopCartInfo(this.skuId);
        if (result.code === 200) {
          this.visible = false;
          // 发送求情
          this.getShopCartListData();
        } else {
          console.log(result.message);
        }
        return;
      }
      const result = await reqDelSelectedShopCartInfo(this.skuIdList);
      if (result.code === 200) {
        this.cartInfoList = this.leftCartInfoList;
        this.visible = false;
      } else {
        console.log(result.message);
      }
    },
    // 商品数量加减
    async changeSkuNum(type, cartInfo, $event) {
      // 变化的初始值
      let oldNum = cartInfo.skuNum;
      switch (type) {
        case "increment":
          if (cartInfo.skuNum < 200) {
            cartInfo.skuNum++;
            this.num++;
          }
          break;
        case "decrement":
          if (cartInfo.skuNum > 1) {
            cartInfo.skuNum--;
            this.num--;
          }
          break;
        case "change":
          let newSkuNum = $event.target.value;
          if (skuNumReg.test(newSkuNum)) {
            cartInfo.skuNum = newSkuNum;
            this.num = newSkuNum - oldNum;
            if (newSkuNum > 200) {
              cartInfo.skuNum = 200;
              this.num = 200 - oldNum;
            }
          } else {
            $event.target.value = oldNum;
          }
          break;
      }
      if (this.num === 0) return;
      if (this.timer) {
        clearTimeout(this.timer);
      }
      this.timer = setTimeout(async () => {
        this.answer = await reqAddOrUpdateCart(cartInfo.skuId, this.num);
        console.log(this.answer);
        if (this.answer.code === 200) {
          console.log("oookkkk");
          this.num = 0;
        } else {
          console.log(this.answer.message);
        }
      }, 1000);
      // const result = await reqAddOrUpdateCart(cartInfo.skuId, num)
      // aaaaa: debounce(reqAddOrUpdateCart(cartInfo.skuId, num), 1000);
      // const result = debounce(reqAddOrUpdateCart(cartInfo.skuId, num), 1000);
    },
  },
  computed: {
    cheakAll: {
      get() {
        return this.cartInfoList.every((cartInfo) => cartInfo.isChecked === 1);
      },
      async set(val) {
        let isChecked = val ? 1 : 0;
        const skuIdList = [];
        this.cartInfoList.forEach((item) => {
          item.isChecked = isChecked;
          skuIdList.push(item.skuId);
        });
        const result = await reqChangeAllCartState(isChecked, skuIdList);
        if (result.code === 200) {
          alert("批量更新ok");
        } else {
          console.log(result.message);
        }
      },
    },
    seletedCount() {
      return this.cartInfoList.reduce((prev, item) => prev + item.isChecked, 0);
    },
    selectedMoney() {
      return this.cartInfoList.reduce(
        (prev, item) => prev + item.skuNum * item.skuPrice * item.isChecked,
        0
      );
    },
  },
  beforeDestroy() {
    clearImmediate(this.timer);
  },
};
</script>

<style lang="less" scoped>
.cart {
  width: 1200px;
  margin: 0 auto;
  h4 {
    margin: 9px 0;
    font-size: 14px;
    line-height: 21px;
  }
  .cart-main {
    .cart-th {
      background: #f5f5f5;
      border: 1px solid #ddd;
      padding: 10px;
      overflow: hidden;
      & > div {
        float: left;
      }
      .cart-th1 {
        width: 25%;
        input {
          vertical-align: middle;
        }
        span {
          vertical-align: middle;
        }
      }
      .cart-th2 {
        width: 25%;
      }
      .cart-th3,
      .cart-th4,
      .cart-th5,
      .cart-th6 {
        width: 12.5%;
      }
    }
    .cart-body {
      margin: 15px 0;
      border: 1px solid #ddd;
      .cart-list {
        padding: 10px;
        border-bottom: 1px solid #ddd;
        overflow: hidden;
        & > li {
          float: left;
        }
        .cart-list-con1 {
          width: 15%;
        }
        .cart-list-con2 {
          width: 35%;
          img {
            width: 82px;
            height: 82px;
            float: left;
          }
          .item-msg {
            float: left;
            width: 150px;
            margin: 0 10px;
            line-height: 18px;
          }
        }
        .cart-list-con4 {
          width: 10%;
        }
        .cart-list-con5 {
          width: 17%;
          .mins {
            border: 1px solid #ddd;
            border-right: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
          }
          input {
            border: 1px solid #ddd;
            width: 40px;
            height: 33px;
            float: left;
            text-align: center;
            font-size: 14px;
          }

          .plus {
            border: 1px solid #ddd;
            border-left: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
          }
        }

        .cart-list-con6 {
          width: 10%;

          .sum {
            font-size: 16px;
          }
        }

        .cart-list-con7 {
          width: 13%;

          a {
            color: #666;
          }
        }
      }
    }
  }
  .cart-tool {
    overflow: hidden;
    border: 1px solid #ddd;

    .select-all {
      padding: 10px;
      overflow: hidden;
      float: left;

      span {
        vertical-align: middle;
      }

      input {
        vertical-align: middle;
      }
    }

    .option {
      padding: 10px;
      overflow: hidden;
      float: left;

      a {
        float: left;
        padding: 0 10px;
        color: #666;
      }
    }

    .money-box {
      float: right;

      .chosed {
        line-height: 26px;
        float: left;
        padding: 0 10px;
      }

      .sumprice {
        width: 200px;
        line-height: 22px;
        float: left;
        padding: 0 10px;

        .summoney {
          color: #c81623;
          font-size: 16px;
        }
      }

      .sumbtn {
        float: right;

        a {
          display: block;
          position: relative;
          width: 96px;
          height: 52px;
          line-height: 52px;
          color: #fff;
          text-align: center;
          font-size: 18px;
          font-family: "Microsoft YaHei";
          background: #e1251b;
          overflow: hidden;
        }
      }
    }
  }
  .btn-footer {
    position: absolute;
    right: 40px;
    bottom: 20px;
    .btn {
      width: 62px;
      height: 32px;
      font-size: 14px;
      margin-left: 16px;
      border-width: 1px;
      border-radius: 10%;
      cursor: pointer;
      &:hover {
        background-color: #fff;
        color: rgb(102, 177, 255);
      }
      &.primary {
        background-color: rgb(102, 177, 255);
        color: #fff;
      }
    }
  }
}
</style>
